package com.banquetmanagementsystem.interceptor;
import com.banquetmanagementsystem.common.Utils.TokenUtil;
import com.banquetmanagementsystem.common.Utils.TokenUtilProperties;
import com.banquetmanagementsystem.common.context.BaseContext;
import com.banquetmanagementsystem.mapper.RefreshTokenMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;


/**
 * @author 86176
 */
@Component
public class JwtTokenInterceptor implements HandlerInterceptor {
    @Resource(name = "tokenUtil")
    private TokenUtil tokenUtil;
    @Resource(name = "tokenUtilProperties")
    private TokenUtilProperties tokenUtilProperties;
    @Resource(name = "refreshTokenMapper")
    private RefreshTokenMapper refreshTokenMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String refreshToken = request.getHeader(tokenUtilProperties.getRefreshTokenName());
        if (refreshToken == null) {
            return response(response);
        }
        if(tokenUtil.verifyRefreshToken(refreshToken)){
            Integer userId = BaseContext.getThreadLocalId();
            Boolean tokenStatus = refreshTokenMapper.selectRefreshTokenStatus(userId);
            if (!tokenStatus) {
                return response(response);
            }
        }
        return true;
    }

    static boolean response(HttpServletResponse response) throws IOException, JSONException {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        JSONObject json = new JSONObject();
        json.put("code", "401");
        json.put("msg", "Token失效");
        json.put("data", "");
        out.print(json);
        out.close();
        return false;
    }
}